package com.deram.ctin.serv.main.api.impl;

import com.deram.ctin.common.bean.UploadResult;
import com.deram.ctin.common.utils.CompareUtils;
import com.deram.ctin.common.utils.DateUtils;
import com.deram.ctin.common.utils.FreeMarkerUtils;
import com.deram.ctin.common.vo.GexfVo;
import com.deram.ctin.serv.enter.api.EnterInfoApi;
import com.deram.ctin.serv.enter.entity.EnterInfo;
import com.deram.ctin.serv.main.api.EnterRelationApi;
import com.deram.ctin.serv.main.consts.EnterRelationConsts;
import com.deram.ctin.serv.main.helper.EnterRelationHelper;
import com.deram.ctin.serv.main.service.EnterRelationService;
import com.deram.ctin.serv.main.vo.EnterRelationVo;
import com.deram.ctin.serv.third.api.QiniuUploadApi;
import com.deram.ctin.serv.third.utils.QiniuUploadUtils;
import freemarker.template.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;

/**
 * @author zhangcm
 * @version 1.0, 2017/9/29
 */
@RestController
public class EnterRelationApiImpl implements EnterRelationApi {

    @Autowired
    private EnterRelationService enterRelationService;
    @Autowired
    private Configuration configuration;
    @Autowired
    private QiniuUploadApi qiniuUploadApi;
    @Autowired
    private EnterInfoApi enterInfoApi;

    @Override
    public EnterRelationVo findRelation(Long id, Integer level) {
        return enterRelationService.findRelation(id, level);
    }

    @Override
    public EnterInfo execGenerateGexf(Long id) {
        EnterInfo enterInfo = enterInfoApi.findById(id);
        // 比对更新时间，有更新则重新生成gexf
        if (null != enterInfo.getGexfUpdateDate() && CompareUtils.with(enterInfo.getGexfUpdateDate(), enterInfo.getUpdateDate()) >= 0) {
            return enterInfo;
        }
        String oldUrl = enterInfo.getGexfUrl();
        // 生成gexf
        EnterRelationVo enterRelationVo = findRelation(id, EnterRelationConsts.LEVEL_MAX);
        GexfVo gexfVo = EnterRelationHelper.parseGexf(enterRelationVo);
        InputStream inputStream = FreeMarkerUtils.createInputStream(configuration, "relationSchema.ftl", gexfVo);
        String name = enterInfo.getName() + "." + DateUtils.getNowLong() + ".gexf";
        UploadResult uploadResult = QiniuUploadUtils.upload(qiniuUploadApi.getConfig(), name, inputStream);
        enterInfo.setGexfUrl(uploadResult.getUrl());
        enterInfo.setGexfUpdateDate(DateUtils.getNow());
        enterInfoApi.save(enterInfo);
        // 删除原先的url
        qiniuUploadApi.delete(oldUrl);
        return enterInfo;
    }
}
